import req from '../request.js'
import { sortMinToNull, getTreeData } from '../../utils/methods'
import { addRoutes } from '../../views/router'
import axios from 'axios'
import { Api } from './ApiClass'
import Vue from 'vue'
import url from '../url-config'

function customTitle(options) {
    options.forEach(item => {
        item.scopedSlots = {
            title: 'title',
        }
        if (item.children && item.children.length) {
            customTitle(item.children)
        }
    })
}

const sortMenu = data => {
    const sort = list => {
        list = sortMinToNull(list)
        list.forEach(item => {
            if (item.children?.length) {
                sort(item.children)
            }
        })
    }
    sort(data)
    return data
}

const getUserHavePromiseMenus = async () => {
    return await req.get('/users/users/queryPermission', {}).then(({ menus, configs }) => {
        return {
            menus: sortMenu(getTreeData(menus || [], 'id', 'permissionPid')),
            configs: sortMenu(getTreeData(configs || [], 'id', 'permissionPid')),
        }
    })
}
const changePassword = ({ surePassword: confirmPassword, newPassword, password: oldPassword }) => {
    return req.post('/users/users/password', {
        confirmPassword,
        newPassword,
        oldPassword,
    })
}
export const formatUserInfo = function (res) {
    const setPromiseBtns = data => {
        const find = (list, parent) => {
            for (let i = list.length - 1; i >= 0; i--) {
                const item = list[i]
                if (parent && item.router.includes(':')) {
                    if (parent.promiseBtns) {
                        parent.promiseBtns[item.router.split(':')[1]] = item.label
                    } else {
                        parent.promiseBtns = {}
                        parent.promiseBtns[item.router.split(':')[1]] = item.label
                    }

                    list.splice(i, 1)
                }
                if (item.children?.length) {
                    find(item.children, item)
                }
            }
        }
        find(data)
        return data
    }
    const menus = getTreeData(res.userPermissions || [], 'id', 'permissionPid')
    res.menus = sortMenu(setPromiseBtns(menus))
    res.roleLevels = res.roleLevels
        ? Object.entries(JSON.parse(res.roleLevels))
              .map(([value, name]) => ({ value: ~~value, name }))
              .filter(({ name }) => name)
        : []
    addRoutes({ menus: res.menus })
    console.log(res.menus, 'res.menus', Vue.prototype)
    return res
}

export const login = ({ one, two, type }) => {
    if (type === 'account') {
        return req.post(`${url.user.login}`, { password: one, username: two })
    }
    return req.post(`${url.user.mobile}`, { code: one, phone: two })
}
export const getSmsCaptcha = ({ password, userName }) => {
    return req.post(`${url.login}?password=${password}&userName=${userName}`)
}

const checkPassword = () => {
    return req.get('/users/users/checkPassword', {})
}
export const getUserInfo = data => req.get(url.getUserInfo, data)

export const menusApi = new Api(url.setting.menus.single)
menusApi.get = data => {
    return req.get(url.setting.menus.all, data)
}
menusApi.sortMenu = sortData => {
    return req.put(url.setting.menus.sort, sortData)
}
export const rolesApi = new Api(url.setting.roles.roles)
rolesApi.getPermissions = data => {
    return req.get(url.setting.roles.permissions, data)
}
rolesApi.postPermissions = data => {
    return req.post(url.setting.roles.permissions, data)
}
export const usersApi = new Api(url.setting.user)
usersApi.changePassword = ({ confirmPassword, newPassword, oldPassword, userId }) => {
    return req.put(url.setting.changePassword, { confirmPassword, newPassword, oldPassword, userId })
}
// ----start----公司管理
export const companyApi = new Api(url.setting.company)
// ----end----公司管理

// ----start----区域管理
export const areaApi = new Api(url.setting.areas.normal)
areaApi.all = data => {
    return req.get(url.setting.areas.all, data)
}
areaApi.children = data => {
    return req.get(url.setting.areas.children, data)
}
export const areaRestApi = new Api(url.setting.areas.rest)
// ----end----区域管理

//froala_eidtor
export const editorApi = {
    getToken: () => req.get(url.fileToken),
    uploadFile: (file, token) => req.post(url.fileBaseUrl + '/' + url.uploadFile),
}

//疑难解答API
export const qaRestApi = new Api(url.qa.rest)

//失信企业API
export const creditEntRestApi = new Api(url.creditEnt.rest)

//失信个人API
export const creditPersonRestApi = new Api(url.creditPerson.rest)

//政策法规API
export const policyRestApi = new Api(url.policy.rest)

//自评模板管理API
export const selfEvaluationTemplateRestApi = new Api(url.selfEvaluationTemplate.rest)
selfEvaluationTemplateRestApi.all = data => req.get(url.selfEvaluationTemplate.all, data)
//通知公告管理api
export const noticeRestApi = new Api(url.notice.rest)

//消息管理API
export const messageRestApi = new Api(url.message.rest)

//消息已读
export const messagePutRead = data => req.put(url.message.putRead, data)

export const messageGetNotRead = () => req.get(url.message.getNotRead)

//添加个人基本信息
export const baseInfoModify = data => req.put(url.user.baseInfoModify, data)
export const baseInfoDetail = () => req.get(url.user.baseInfoDetail)

//首页

export const handleListGet = () => req.get(url.home.handleList)
export const mapDeclareListGet = params => req.get(url.home.mapDeclareList, params)
export const currentNodeGet = () => req.get(url.home.currentNode)
export const currentScoreGet = () => req.get(url.home.currentScore)

//统计
export const scoreStatisticsGet = () => req.get(url.statistics.scoreStatistics)
export const jjScoreStatisticsGet = () => req.get(url.statistics.jjScoreStatistics)
export const xianUpDownScoreGet = () => req.get(url.statistics.xianUpDownScore)
